package com.lyfam.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;

public class SpringVaadinApplicationServlet extends AbstractApplicationServlet
{
    private ApplicationContext context;
    private Class<? extends Application> applicationClass;
    private String applicationBean;
    
    @Override
    public void init(ServletConfig servletConfig) throws ServletException
    {
        super.init(servletConfig);
        
        applicationBean = servletConfig.getInitParameter("applicationBean");
        if ("".equals(applicationBean))
        {
            throw new ServletException(
                    "ApplicationBean parameter not specified in servlet parameters");
        }
        
        context = WebApplicationContextUtils.getRequiredWebApplicationContext(
                servletConfig.getServletContext());
        applicationClass = context.getType(applicationBean);
    }
    
    @Override
    protected Class<? extends Application> getApplicationClass() throws ClassNotFoundException
    {
        return applicationClass;
    }

    @Override
    protected Application getNewApplication(HttpServletRequest request) throws ServletException
    {
        return (Application) context.getBean(applicationBean);
    }

}
